﻿using Furion.DatabaseAccessor;
using iWare.Wms.WorkerService.ThirdDB;
using Yitter.IdGenerator;

namespace iWare.Wms.WorkerService
{
    public class ProjectERP : BackgroundService
    {
        private readonly ILogger<ProjectERP> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public ProjectERP(ILogger<ProjectERP> logger,
                      IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        // 启动
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }

        // 执行逻辑
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //定时同步项目信息
                //await AddProject();

                await Task.Delay(24 * 60 * 60 * 1000, stoppingToken);
            }
        }

        #region 定时同步项目信息
        /// <summary>
        /// 定时同步项目信息
        /// </summary>
        /// <returns></returns>
        public async Task AddProject()
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;
                var respository = Db.GetSqlRepository<ERPDbContextLocator>();

                //获取仓储实体
                var _projectManageRep = Db.GetRepository<ProjectManage>(services);

                var whereTime = DateTime.Now.AddMonths(-2).ToString("yyyyMMdd");

                //查询近两月的项目编号信息
                var projectManageList = await respository
                .SqlQueryAsync<ProjectManageErpInput>
                (@"select NO001, --项目编号
	                      NO002, --项目名称
	                      NO003  --项目说明
                   from CMSNO where CREATE_DATE> '" + whereTime + "'");

                var addProjectManageList = new List<ProjectManage>();

                foreach (var item in projectManageList)
                {
                    var isExists = await _projectManageRep
                        .AnyAsync(u => u.Code.Equals(item.NO001) && u.Name.Equals(item.NO002));

                    //不存在执行新增操作
                    if (!isExists)
                    {
                        var addProjectManageModel = new ProjectManage
                        {
                            Id = YitIdHelper.NextId(),
                            Code = item.NO001 == null ? "" : item.NO001.Trim(),
                            Name = item.NO002 == null ? "" : item.NO002.Trim(),
                            Describe = item.NO003 == null ? "" : item.NO003.Trim(),
                            CreatedUserName = "LES SYSTEM",
                            CreatedTime = DateTimeOffset.Now
                        };
                        addProjectManageList.Add(addProjectManageModel);
                    }
                }

                // 批量新增
                await _projectManageRep.InsertNowAsync(addProjectManageList);

                Console.WriteLine("定时同步项目信息");
            }
        }

        #endregion

        // 停止
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}
